//
//  HistoryTransactionViewController.m
//  MHO
//
//  Created by Hien NV on 12/15/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "HistoryTransactionViewController.h"
#import "Lib.h"
#import "HistoryTransaction.h"
#import "PullRefreshAndLoadMoreViewController.h"

@interface HistoryTransactionViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
{
    UIView* loadingFooterView;
    UIActivityIndicatorView* loadingActivyIndicator;
    BOOL isLoadingMore, isLoading;
    UIRefreshControl* refreshControl;
}
@property (nonatomic, weak) IBOutlet UITableView* tableView;
@property (nonatomic, strong) NSString* actionId;
@property (nonatomic, strong) NSMutableArray* data;
@property (nonatomic, assign) int currentPage;
@end

@implementation HistoryTransactionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[self.navibarView leftButton] setImage:[UIImage imageNamed:@"btn_back"] forState:UIControlStateNormal];
    [[self.navibarView leftButton] setImage:[UIImage imageNamed:@"btn_back_focus"] forState:UIControlStateHighlighted];
    int d[] = {
        3, 2, 5, 1
    };
    self.actionId = [NSString stringWithFormat:@"%d", d[self.index]];
    self.currentPage = 0;
    UIRefreshControl* control = [[UIRefreshControl alloc] init];
    [control addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    
    UIView *refreshView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.tableView insertSubview:refreshView atIndex:0]; //the tableView is a IBOutlet
    [refreshView addSubview:control];
    
    refreshControl = control;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadData];
}

- (void)refresh:(id)sender {
    [self loadData];
}

- (void)loadData {
    self.currentPage = 0;
    isLoading = YES;
    [self loadDataFromPage:self.currentPage];
}

- (void)loadMore {
    self.currentPage++;
    [self loadDataFromPage:self.currentPage];
}

- (void)loadDataFromPage: (int)page {
    if (self.data == nil) {
        self.data = [[NSMutableArray alloc] init];
    }
    else {
        [self.data removeAllObjects];
    }
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* user = [Lib stringForKey:@"Email"];
        NSString* token = [Lib md5:[NSString stringWithFormat:@"%@%@%d%d%@%@", user, self.actionId, page, 10, kServiceId, kServiceToken]];
        NSString* url = [NSString stringWithFormat:@"http://paygate.mho.vn/Transfer/HistoryTransaction?userId=%@&actionId=%@&serviceId=%@&token=%@&pageIndex=%d&pageSize=%d", user, self.actionId, kServiceId, token, page, 10];
        NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
        if (ret) {
            SBJsonParser* parser = [[SBJsonParser alloc] init];
            id dict = [parser objectWithString:ret];
            if (dict) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Lib removeLoadingView];
                    if (isLoading) {
                        isLoading = NO;
                        [refreshControl endRefreshing];
                    }
                    BOOL isSuccess = [dict[@"IsSuccess"] boolValue];
                    NSString* message = dict[@"Message"];
                    if (isSuccess) {
                        NSArray* data = dict[@"ListItems"];
                        for (id d in data) {
                            if (d) {
                                HistoryTransaction* h = [HistoryTransaction historyTransactionWithDictionary:d];
                                [self.data addObject:h];
                            }
                        }
                        
                        [self.tableView reloadData];
                    }
                    else {
                        [Lib showMessage:message title:@""];
                    }
                });
            }
        }
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] init];
    }
    
    cell.contentView.backgroundColor = [UIColor viewFlipsideBackgroundColor];
    cell.backgroundColor = [UIColor viewFlipsideBackgroundColor];
    
    HistoryTransaction* h = self.data[indexPath.row];
    cell.textLabel.text = h.transactionDate;
    cell.detailTextLabel.text = h.value;
    
    return cell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


- (void)addLoadingFooterView
{
    loadingFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
    loadingFooterView.backgroundColor = [UIColor clearColor];
    
    
    loadingActivyIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [loadingActivyIndicator setCenter:CGPointMake(160, REFRESH_HEADER_HEIGHT / 2)];
    [loadingActivyIndicator setHidesWhenStopped:YES];
    
    [loadingFooterView addSubview:loadingActivyIndicator];
    [self.tableView setTableFooterView:loadingFooterView];
    self.tableView.tableFooterView.hidden = YES;
}

//

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!isLoadingMore && !isLoading && scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height && scrollView.contentSize.height > scrollView.frame.size.height)
    {
        [self startLoadingMore];
    }
}

- (void)startLoadingMore
{
    isLoadingMore = YES;
    self.tableView.tableFooterView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        [loadingActivyIndicator startAnimating];
        
    }];
    [self loadMore];
}

- (void)stopLoadingMore
{
    isLoadingMore = NO;
    [loadingActivyIndicator stopAnimating];
    self.tableView.tableFooterView.hidden = YES;
}


@end
